document.addEventListener('DOMContentLoaded', () => {
    const sitesDiv = document.getElementById('sites');
    const newSiteInput = document.getElementById('newSite');
    const newMessageInput = document.getElementById('newMessage');
    const addSiteButton = document.getElementById('addSite');

    loadMonitoredSites();

    addSiteButton.addEventListener('click', async () => {
        const site = newSiteInput.value;
        const message = newMessageInput.value;

        // 检查网址和消息是否都非空
        if (site && message) {
            try {
                const url = new URL(site);
                const hostname = url.hostname;
                await addMonitoredSite(hostname, message); // 等待添加监控站点完成
                newSiteInput.value = '';
                newMessageInput.value = '';

                // 向后台页面发送消息更新 monitoredSites
                chrome.runtime.sendMessage({ action: 'updateMonitoredSites' });

            } catch (error) {
                console.error('Invalid URL:', error);
                // 可以在这里添加处理无效网址的逻辑，比如显示错误信息给用户
            }
        } else {
            console.error('Site and message are required.');
            // 可以在这里添加处理空输入的逻辑，比如显示错误信息给用户
        }
    });

    async function loadMonitoredSites() {
        try {
            const result = await getMonitoredSitesFromStorage();
            if (result.monitoredSites) {
                for (const [site, message] of Object.entries(result.monitoredSites)) {
                    addSiteElement(site, message);
                }
            }
        } catch (error) {
            console.error('Error loading monitored sites:', error);
        }
    }

    function getMonitoredSitesFromStorage() {
        return new Promise((resolve, reject) => {
            chrome.storage.local.get(['monitoredSites'], (result) => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve(result);
                }
            });
        });
    }

    async function addMonitoredSite(site, message) {
        try {
            let result = await getMonitoredSitesFromStorage();
            const monitoredSites = result.monitoredSites || {};

            monitoredSites[site] = message;
            await setMonitoredSitesToStorage(monitoredSites); // 等待存储操作完成
            addSiteElement(site, message);
        } catch (error) {
            console.error('Error adding monitored site:', error);
        }
    }

    function setMonitoredSitesToStorage(monitoredSites) {
        return new Promise((resolve, reject) => {
            chrome.storage.local.set({ monitoredSites: monitoredSites }, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });
    }

    function addSiteElement(site, message) {
        const siteDiv = document.createElement('div');
        siteDiv.className = 'site';
        siteDiv.textContent = `${site}: ${message}`;
        const deleteButton = document.createElement('button');
        deleteButton.textContent = 'Delete';
        deleteButton.addEventListener('click', async () => {
            await deleteMonitoredSite(site); // 等待删除操作完成
            siteDiv.remove();

            // 向后台页面发送消息更新 monitoredSites
            chrome.runtime.sendMessage({ action: 'updateMonitoredSites' });
        });
        siteDiv.appendChild(deleteButton);
        sitesDiv.appendChild(siteDiv);
    }

    async function deleteMonitoredSite(site) {
        try {
            let result = await getMonitoredSitesFromStorage();
            const monitoredSites = result.monitoredSites || {};
            delete monitoredSites[site];
            await setMonitoredSitesToStorage(monitoredSites); // 等待存储操作完成
        } catch (error) {
            console.error('Error deleting monitored site:', error);
        }
    }
});
